import 'package:ddframework/mixin/dd_controller_mixin.dart';
import 'package:flutter/material.dart';
import 'package:ddframework/global/global.dart';

class DDTabbarWidget extends StatefulWidget {
  final Color backgroundColor;
  final DDTabbarController? controller;
  final List<Widget> pages;
  final List<String> titles;
  final List<Widget> icons;
  final List<Widget> selectedIcons;
  final List<Color> colors;
  final List<Color> selectedColors;
  DDTabbarWidget({
    Key? key,
    this.backgroundColor = const Color(0xffffffff),
    this.controller,
    this.pages = const [],
    this.titles = const [],
    this.icons = const [],
    this.selectedIcons = const [],
    this.colors = const [],
    this.selectedColors = const [],
  }) : super(key: key);
  @override
  _DDTabbarWidgetState createState() => _DDTabbarWidgetState();
}

class _DDTabbarWidgetState extends State<DDTabbarWidget> {
  late DDTabbarController _controller;
  // 当前激活的widget 用于懒加载
  late List<Widget> _currentActivePages;

  @override
  void initState() {
    super.initState();
    _controllerAction();
    _generatePages();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: widget.backgroundColor,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Expanded(
            child: IndexedStack(
              children: _currentActivePages,
              sizing: StackFit.expand,
              index: _controller._index,
            ),
            flex: 1,
          ),
          Divider(
            color: Colors.black26,
            height: .5,
          ),
          DDTabbarBottomWidget(
            titles: widget.titles,
            icons: widget.icons,
            selectedColors: widget.selectedColors,
            selectedIcons: widget.selectedIcons,
            colors: widget.colors,
            selectedIndex: _controller._index,
            onTap: (index) {
              // _controller.changeToIndex(index); // 将内部改变索引事件，上升到全局，供外部监听使用。
              if (_controller._index == index) {
                return;
              }
              // Global.storeAgent.dispatch(name: GlobalActions.changeTabbarIndex, data: index);
            },
          ),
        ],
      ),
    );
  }

  void _controllerAction() {
    _controller = widget.controller ?? DDTabbarController(0);
    // 外部触发索引变更
    _controller.addListener("changeIndex", (pars) {
      _controller._index = pars;
      _currentActivePages[_controller.currentIndex] = widget.pages[_controller.currentIndex];
      setState(() {});
    });
  }

  void _generatePages() {
    _currentActivePages = [];
    for (var i = 0; i < widget.pages.length; i++) {
      if (i == _controller._index) {
        _currentActivePages.add(widget.pages[i]);
      } else {
        _currentActivePages.add(const Center());
      }
    }
  }
}

// 抽象底部逻辑，优化构建速度
class DDTabbarBottomWidget extends StatelessWidget {
  final List<String> titles;
  final List<Widget> icons;
  final List<Widget> selectedIcons;
  final List<Color> colors;
  final List<Color> selectedColors;
  final int selectedIndex;
  final Function(int index)? onTap;
  const DDTabbarBottomWidget({
    Key? key,
    this.titles = const [],
    this.icons = const [],
    this.selectedIcons = const [],
    this.colors = const [],
    this.selectedColors = const [],
    this.selectedIndex = 0,
    this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).padding.bottom + 49,
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: _generateItem(),
      ),
    );
  }

  List<Widget> _generateItem() {
    List<Widget> items = [];
    for (var i = 0; i < titles.length; i++) {
      DDTabBarItem item = DDTabBarItem(
        itemWidth: Global.screenWidth / titles.length,
        icon: icons[i],
        selectedIcon: selectedIcons[i],
        title: titles[i],
        color: colors[i],
        selectedColor: selectedColors[i],
        selected: selectedIndex == i,
        onTap: () {
          onTap!(i);
        },
      );
      items.add(item);
    }
    return items;
  }
}

/// 简单的tabbarItem
class DDTabBarItem extends StatelessWidget {
  final String title;
  final Widget icon;
  final Widget selectedIcon;
  final Color color;
  final Color selectedColor;
  final Function() onTap;
  final bool selected;
  final double itemWidth;
  DDTabBarItem({
    Key? key,
    required this.title,
    required this.icon,
    required this.selectedIcon,
    required this.color,
    required this.selectedColor,
    required this.onTap,
    this.selected = false,
    required this.itemWidth,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: itemWidth,
      child: GestureDetector(
        onTap: onTap,
        behavior: HitTestBehavior.opaque, // 这句话的目的是为了空白区域也能响应点击事件
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 4, bottom: 2),
              child: selected ? selectedIcon : icon,
            ),
            Expanded(
              child: Text(
                title,
                style: TextStyle(
                  color: selected ? selectedColor : color,
                  fontSize: 12,
                  decoration: TextDecoration.none,
                  fontWeight: FontWeight.normal,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// tabbar控制器
class DDTabbarController with DDControllerMixin {
  DDTabbarController(int index) {
    _index = index;
  }
  var _index = 0;
  int get currentIndex {
    return _index;
  }

  void changeToIndex(int index) {
    _index = index;
    dispatch('changeIndex', index);
  }
}
